<?php
namespace app\user\model\user;

use app\common\model\BaseModel;
use app\user\logic\user\Account as User;

/**
 * 消息通知模型
 */
class NotifyMessage extends BaseModel
{

    /**
     * 表名
     * @var string
     */
    protected $name = 'notify_message';

    /**
     * 设置自动写入时间
     * @var boolean
     */
    protected $autoWriteTimestamp = true;

    /**
     * 定义字段类型
     * @var array
     */
    protected $type = [
        'id'            => 'integer',
        'create_time'   => 'integer',
    ];

/* 查询范围 */
    public function scopeUnread($query, $type = 0)
    {
        // 1、2为系统消息，systemNotify模型
        if ($type == 3) {       // 评论类
            $query->where('notify_type', 'IN', '1,2');
        } else if ($type == 4) {// 提问类
            $query->where('notify_type', 'IN', '3');
        }

        $query->where('recive_user_id', request()->mid);
        $query->where('is_read', 0);
    }

    public function scopeCommentList($query, $is_read = 2)
    {
        $query->where('recive_user_id', request()->mid)->where('notify_type', 'IN', '1,2,4,5');

        if ( in_array($is_read, [0,1]) ) {
            $query->where('is_read', $is_read);
        }
    }

    public function scopeCourseReplyList($query)
    {
        $query->where('recive_user_id', request()->mid)->where('notify_type', 1);
    }

    public function scopeTopicReplyList($query)
    {
        $query->where('recive_user_id', request()->mid)->where('notify_type', 2);
    }

    public function scopeQuestionReplyList($query, $is_read = 2)
    {
        $query->where('recive_user_id', request()->mid)->where('notify_type', 'IN', '3,6');
        if ( in_array($is_read, [0,1]) ) {
            $query->where('is_read', $is_read);
        }
    }

/* 关联 */

    public function sendUser()
    {
        return $this->belongsTo(User::class, 'send_user_id')->bind([
            'send_user_nick_name' => 'nick_name',
            'send_user_avatar_url' => 'avatar_url'
        ]);
    }

}
